#!/bin/sh

set -e

config="${XDG_CONFIG_HOME:-${HOME}/.config}/guc/config.json"

start_dir="$PWD"
home_escaped=$(echo "$HOME" | sed 's/\//\\\//g')


if [ ! -e "$config" ]; then
	echo "${config} does not exist"
	exit 1
fi

jq -c '.[]' "$config" | while read item; do
	name=$(echo "$item" | jq -r '.name')
	path=$(echo "$item" | jq -r '.path' | sed "/^~.*/ s/./${home_escaped}/")
	branch=$(echo "$item" | jq -r '.branch')

	cd "$path"

	remote=$(git remote)

	if [ -z "$remote" ]; then
		echo "${name} has no upstream set"
		continue
	fi

	git fetch -q "$remote" "$branch" || (echo "Failed to fetch ${branch} for ${name}" && exit 128)
	updates=$(git rev-list "${remote}/${branch}" ^"${branch}" --count)

	if [ "$updates" -gt 0 ]; then
		echo "${name} has ${updates} updates on ${branch}"
	else
		echo "${name} is up to date"
	fi
done

cd "$start_dir"
